define(function (require, exports, module) {
    var angular = require('angular');
    require("pagination");
    require("angular-ui");
    require('/public/js/myservice/contract/contract-common');
    var myMath = require('/public/js/myservice/common/my-math');
    var util = require("util");
    var api_prefix = G_CONFIG["api_prefix"]; //api前缀

    angular.module('ContractBalance', [])
        .filter('backAmount', function () {
            return function (bkamount, signamount , balanceshouldamount) {
                var amount = 0;
                amount = signamount - balanceshouldamount;
                return amount;
            }
        })
        .filter('sumAmount', function () {
            return function (lists) {
                var amount = 0;
                $.each(lists||[], function (i, d) {
                    amount = myMath.add(amount, parseFloat(d.amount));
                });
                return amount;
            }
        })
        .filter('sumBalanceAmount', function () {
            return function (lists) {
                var amount = 0;
                $.each(lists||[], function (i, d) {
                    amount = myMath.add(amount, parseFloat(d.balance_amount));
                });
                return amount;
            }
        })
        .service('backAmountService', ['$rootScope',function($rootScope) {
            var service = {
                onBackEditShow: function ($dialog, $dialogScope,record) {
                    $dialogScope.backrecord = {};
                    if(record){
                        $dialogScope.backrecord = record;
                        setTimeout(function () {
                            if ($dialogScope.backrecord.area_name) {
                                $('#idAreaid').length && $('#idAreaid').data('select2').updateSelection({text: $dialogScope.backrecord.area_name || $dialogScope.backrecord.area_id});
                            }
                        },5);
                    }
                    $dialogScope.ddl2Areaid = '';
                    $dialogScope.ddl2IsReceived = '';
                    $dialogScope.ddlConfigRecelved = {
                        allowClear: false,
                        data: [],
                        placeholder: '是否收票'
                    };
                    $dialogScope.ddlConfigRecelved.data = [
                        {id: 1, text: '是'},
                        {id: 0, text: '否'},
                    ];
                    // 所属区域下拉框处理
                    $dialogScope.ddlConfigBackAreaid = {
                        allowClear: false,
                        ajax: {
                            url: api_prefix + "contract/get-area-info",
                            dataType: 'json',
                            delay: 250,
                            data: function (term) {
                                return {
                                    keyword: term,
                                    limit: 10
                                };
                            },
                            results: function (json, page) {
                                var data = [];
                                if (json.retCode === "0") {
                                    data = json.data;
                                    $.each(data, function (i, d) {
                                        d.text = d.BUName;
                                        d.id = d.BUGUID;
                                    });
                                }
                                return {results: data};
                            },
                            processResults: function (data, page) {
                                // parse the results into the format expected by Select2.
                                // since we are using custom formatting functions we do not need to
                                // alter the remote JSON data
                                return {
                                    results: data.items
                                };
                            },
                            cache: true
                        }
                    };
                },
                editBackSave: function($dialog,$dialogScope,contractid,callback)
                {
                    /**
                     * 保存
                     */
                    var post_data = {};
                    post_data.backrecord = $dialogScope.backrecord;
                    post_data.contractid = contractid;
                    if(!post_data.backrecord.area_id){
                        util.alert('请选择区域!');
                        return false;
                    }
                    if(!post_data.backrecord.back_amount || post_data.backrecord.back_amount==0){
                        util.alert('请填写金额!');
                        return false;
                    }
                    var url = api_prefix + "/contract/save-back-amount";
                    util.myAjax({
                        url: url,
                        type: "POST",
                        context: this,
                        data: post_data,
                        success: function (json) {
                            if (json.retCode == 0) {
                                util.alert("保存成功");
                                if (callback) {
                                    callback();
                                }
                            } else {
                                util.alert("保存失败：" + json.errMsg);
                            }
                        }
                    });
                },
                deleteBack: function(record,callback){
                    /**
                     * 删除
                     */
                    var post_data = {};
                    post_data.back_amount_id = record.back_amount_id;
                    post_data.contractid = record.contract_id;
                    var url = api_prefix + "/contract/delete-back-amount";
                    util.myAjax({
                        url: url,
                        type: "POST",
                        context: this,
                        data: post_data,
                        success: function (json) {
                            if (json.retCode == 0) {
                                util.alert("删除成功");
                                if (callback) {
                                    callback();
                                }
                            } else {
                                util.alert("删除失败：" + json.errMsg);
                            }
                        }
                    });
                }
            }
            return service;
        }])
        .controller('contractBalanceCtrl', ['$scope' ,'$location', '$routeParams', 'contractCommonService','backAmountService', function ($scope, $location, $routeParams, contractCommonService,backAmountService) {
            $scope.backAmountService = backAmountService;
            $scope.contractBaseInfo = {};
            var contractId = $routeParams.id;

            $scope.contractTypeName = $location.search().contractType;
            $scope.contractTypes = {};
            $scope.ddl2BackReceiveStatus = '';

            //获取合同类别
            contractCommonService.getContractTypes(function (data) {
                $scope.contractTypes = data;
                $scope.contractTypeCode = $scope.contractTypes[$scope.contractTypeName];
                $scope.$applyAsync();
            });

            // 客户下拉框处理
            $scope.ddlConfigBalanceType = {
                allowClear: false,
                data: [],
                placeholder: '结算类型'
            };
            //结算类型 0：标准结算 1：特价结算 2：明折结算
            $scope.ddlConfigBalanceType.data = [
                {id: 0, text: '标准结算'},
                {id: 1, text: '特价结算'},
                {id: 2, text: '明折结算'}];

            $scope.ddlConfigApplicationName = {
                allowClear: true,
                data: [],
                placeholder: '应用名称'
            };

            // 客户下拉框处理
            $scope.ddlConfigBackReceiveStatus = {
                allowClear: false,
                data: [],
                placeholder: '是否收票'
            };
            //是否已收票 0：否 1：是
            $scope.ddlConfigBackReceiveStatus.data = [
                {id: 0, text: '否'},
                {id: 1, text: '是'}];

            $scope.canAddNewBalance = 0;

            $scope.getContract = function () {
                //获取合同信息
                contractCommonService.getContract(contractId, function (data) {
                    $scope.contractBaseInfo = data.contract;
                    var customername = data.contract.customer_name;
                    var sumsharebalanceamount = 0;
                    var balancerate = 0.5;
                    $scope.payovers = data.payover;
                    $.each($scope.payovers, function (idx,objitem) {
                        objitem["balance_type_name"] = $scope.ddlConfigBalanceType.data[objitem.balance_type].text;
                        objitem["editMode"] = objitem["edit_mode"];
                        balancerate = 0.5;
                        if(customername =='碧桂园房地产' && objitem["editMode"]==2 && objitem['balance_rate']==0 && $scope.contractTypeCode == 5){
                            balancerate = 0.25
                            objitem['balance_rate'] = balancerate * 100;
                            objitem['balance_amount'] = balancerate * objitem['amount'];
                        }
                    });
                    $scope.ddlConfigApplicationName.data = [];
                    $.each(data.application, function (idx,item) {
                        //sumsharebalanceamount += parseFloat(item['share_balance_amount']);
                        if(item.application_id == '2f24ad79-4bca-42ef-a275-5adb74adfd90' ||
                            item.application_id == '2fd5ae7b-889b-409d-8893-9bae7ddc1e7d' ||
                            item.application_id == '8da7bb48-c64f-436e-a67f-4ea1c06bc7aa' ||
                            item.application_id == 'bd3c0d01-fa7f-4ca8-a493-9b3b5c8d8ddb' ||
                            item.application_id == '0df6297e-e421-4a35-aa34-497c59a529ba' ||
                            item.application_id == '2e482083-a008-4ea5-b38a-8f3024df512a' ||
                            item.application_id == '938ed790-4b63-465a-9eef-3e88c010e3d7' ||
                            item.application_id == '70883d11-7f63-46f4-a2b6-16f94d3132fe' ||
                            item.application_id == '605fc722-0a73-4578-b74f-b2436fd9367e' ||
                            item.application_id == '2c914692-3a81-4969-9630-c5fa946540cb' ||
                            item.application_id == '18b9fb27-b585-42a6-9556-25d8eecb9a26' ||
                            item.application_id == '606ec8dc-a4d5-4e37-a4a6-2cbe1d16c460' ||
                            item.application_id == 'dd46b258-8c4d-4614-9bd0-c12212fe4444')
                        {
                            $scope.ddlConfigApplicationName.data.push({id:item.application_id,text:item.application_name});
                            $scope.canAddNewBalance = 1;
                        }
                    });
                    //$scope.contractBaseInfo.balance_should_amount = sumsharebalanceamount;
                    $scope.shipments = data.shipment;
                    $scope.backamountlist = data.backamountlist;
                    backamount = 0;
                    $.each(data.backamountlist,function(idx,itm){
                        backamount += parseFloat(itm.back_amount);
                    });
                    $scope.back_amount = backamount;
                    $scope.$applyAsync();
                });
            };

            $scope.$watch('contractBaseInfo.balance_should_amount', function (itemValue) {
                //util.alert(itemValue);
                $scope.contractBaseInfo.balance_amount = itemValue;
            });

            $scope.showmsg = function(msg){
                util.alert(msg);
            };

            ////获取结算返款信息
            //contractCommonService.getContractBalanceInfo(contractId, function (data) {
            //    $scope.balanceInfo = data.contract;
            //    $scope.applications = data.applications;
            //    $scope.balanceInfo.balance_rate = myMath.mul($scope.balanceInfo.balance_rate, 100);
            //    $scope.$applyAsync();
            //});


            //保存结算信息
            $scope.save = function () {
                var backdate = $scope.contractBaseInfo.back_date;
                var backamount = $("#back_amount").val();
                var balanceamount = 0;
                if([2,7].indexOf($scope.contractTypeCode) == -1){
                    balanceamount = $("#balance_amount").val();
                }else{
                    balanceamount = $scope.contractBaseInfo.balance_amount;
                };

                $scope.contractBaseInfo.back_amount = backamount;
                $scope.contractBaseInfo.balance_amount = balanceamount;
                var post_data = {contractBaseInfo: $scope.contractBaseInfo};
                var url = api_prefix + "/contract/update-contract-account";
                
                util.myAjax({
                    url: url,
                    type: "POST",
                    context: this,
                    data: post_data,
                    success: function (json) {
                        if (json.retCode === "0") {
                            util.alert('保存成功');
                            $scope.getContract();
                        } else {
                            util.alert("保存失败：" + json.errMsg);
                        }
                    }
                });
            };
            
            $scope.newPayover = function () {
                var items = $scope.payovers;
                var id = items.length ? items[0].id + 1 : 1;

                var payoverinfo = {
                    id: id,
                    application_name: '',
                    authorize_time: '',
                    authorization_numeric: '',
                    balance_type: '',
                    balance_rate: '',
                    balance_amount: '',
                    editMode: '1'
                };
                items.unshift(payoverinfo);
            }

            $scope.editPayover = function (item,idx) {
                //先保存原始数据,取消时使用
                item.orginalData = angular.copy(item);
                item.editMode = 2;
            };

            $scope.cancelPayover = function (item,idx) {
                if(item.editMode == '1'){
                    var items = $scope.payovers;
                    items.splice(idx, 1);
                }else {
                    angular.extend(item, item.orginalData);
                    item.editMode = 0;
                }
            };

            $scope.savePayover = function (item) {
                if(item.editMode == 1) {
                    if (!item.application_id || item.application_id == '') {
                        util.alert('请选择应用!');
                        return;
                    }
                    if (!item.authorize_time || item.authorize_time == '') {
                        util.alert('请选择开通时间!');
                        return;
                    }
                    if (!item.authorization_numeric || item.authorization_numeric == '' || item.authorization_numeric == 0) {
                        util.alert('请填写授权数量!');
                        return;
                    }
                }
                if(!item.balance_type || item.balance_type==''){
                    util.alert('请选择结算类型!');
                    return;
                }
                //结算比例支持为0
                //if(!item.balance_rate || item.balance_rate == 0){
                //    util.alert('请设置结算比例!');
                //    return;
                //}
                if(item.balance_rate<0 || item.balance_rate>100){
                    util.alert('结算比例必须在0-100范围内!');
                    return;
                }
                //结算金额支持为0
                //if(!item.balance_amount || item.balance_amount == 0){
                //    util.alert('请填写结算金额!');
                //    return;
                //}

                var url = api_prefix + 'contract/save-payover-balance';
                var balancedata = {
                    oid: item.contract_payover_id,
                    contractid: $scope.contractBaseInfo.contract_id,
                    contractcode: $scope.contractBaseInfo.contract_code,
                    applicationid: item.application_id,
                    authorizetime: item.authorize_time,
                    stock_out_code: item.stock_out_code,//出库单号-新加
                    stock_out_id: item.stock_out_id,//出库单GUID-新加
                    authorizationnumeric: item.authorization_numeric,
                    balancetype: item.balance_type,
                    balancerate: item.balance_rate,
                    balanceamount: item.balance_amount,
                    editmode: item.editMode,
                    authorize_period: item.authorize_period
                };
                $scope.contractBaseInfo.balance_amount = $("#sumBalanceAmount").text();
                var post_data = {contractBaseInfo: $scope.contractBaseInfo,balancedata:balancedata};
                $.ajax({
                    url: url,
                    type: 'post',
                    dataType: 'json',
                    data: post_data,
                    success: function (res) {
                        if (res.retCode == "0") {
                            util.alert('保存成功');
                            $scope.getContract();
                        } else {
                            util.alert(res.errMsg);
                        }
                    },
                    error: function () {
                        util.alert('系统维护，请稍候重试！');
                    }
                });
            };

            $scope.getContract();
        }]);
});